package com.zhkj.txg.module.product.ui

import android.Manifest
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Typeface
import android.net.Uri
import android.text.TextUtils
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.core.view.postDelayed
import androidx.core.widget.NestedScrollView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.TimeUtils
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.tbruyelle.rxpermissions2.RxPermissions
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.ScreenUtil
import com.zhkj.lib.utils.SpanUtil
import com.zhkj.txg.R
import com.zhkj.txg.base.CustomApplication
import com.zhkj.txg.module.login.ui.LoginActivity
import com.zhkj.txg.module.order.ui.OrderSubmitActivity
import com.zhkj.txg.module.product.adapter.BannerUIEntity
import com.zhkj.txg.module.product.adapter.ProductAdapter
import com.zhkj.txg.module.product.adapter.ProductBannerAdapter
import com.zhkj.txg.module.product.adapter.ProductRecommendAdapter
import com.zhkj.txg.module.product.entity.ProductResponse2
import com.zhkj.txg.module.product.popup.ProductSpecPopupWindow
import com.zhkj.txg.module.product.vm.ProductViewModel
import com.zhkj.txg.utils.ConfigManager
import com.zhkj.txg.utils.GridItemDecoration
import com.zhkj.txg.utils.ImageUtils
import kotlinx.android.synthetic.main.activity_product_detail_2.*
import kotlinx.android.synthetic.main.activity_product_detail_2.detailView
import kotlinx.android.synthetic.main.activity_product_detail_2.ivProductTop
import kotlinx.android.synthetic.main.activity_product_detail_2.scrollProduct
import kotlinx.android.synthetic.main.activity_product_detail_2.tabProduct
import kotlinx.android.synthetic.main.activity_product_detail_2.titleProduct
import kotlinx.android.synthetic.main.item_product_group_bar_2.*
import kotlinx.android.synthetic.main.item_product_recommend.*
import kotlinx.android.synthetic.main.item_product_top_2.*
import java.util.*
import kotlin.collections.ArrayList


class ProductDetailActivity2 : ViewModelActivity<ProductViewModel>() {

    companion object {
        private const val PRODUCT_ID = "productId"
        private const val SHOP_ID = "SHOP_ID"
        fun normalProduct(context: Context, id: Int, singleTop: Boolean = true, shopId: Int = 0) {
            val intent = Intent(context, ProductDetailActivity2::class.java).putExtra(PRODUCT_ID, id).putExtra(SHOP_ID, shopId)
            if (singleTop) intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
            context.startActivity(intent)
        }
    }

    private val tabAdapter = ProductAdapter().apply {
        setOnItemClickListener { _, _, position ->
            when (position) {
                1 -> {
                    val commentTop = recommendView.top
                    val scrollY = commentTop - titleProduct.height
                    scrollProduct.smoothScrollTo(0, scrollY)
                }
                2 -> {
                    val detailTop = detailView.top
                    val scrollY = detailTop - titleProduct.height
                    scrollProduct.smoothScrollTo(0, scrollY)
                }
                else -> scrollProduct.smoothScrollTo(0, 0)
            }
        }
    }
    private val bannerAdapter = ProductBannerAdapter().apply {
        setOnItemClickListener { _, _, position ->
            if (data[position].type == BannerUIEntity.IMAGE) {
                val list: ArrayList<String> = ArrayList()
                val url = data[position].imageUrl
                var index = 0
                data.forEach {
                    if (it.type == BannerUIEntity.IMAGE) {
                        list.add(it.imageUrl ?: "")
                        if (it.imageUrl == url) index = list.lastIndex
                    }
                }
                WatcherActivity.open(this@ProductDetailActivity2, list, index)
            }
        }
    }
    private val productSpecPopupWindow: ProductSpecPopupWindow by lazy {
        ProductSpecPopupWindow(this, { specId, goodsNum -> // 立即购买按钮回调
            if (AccountManager.getToken().isEmpty()) { // 未登录，跳转登录
                LoginActivity.jump2Login(this@ProductDetailActivity2)
                return@ProductSpecPopupWindow
            }
            viewModel.productLiveData2.value?.response?.data?.let {
                if (it.activeType == 1) {
                    val nowTime = TimeUtils.getNowMills()
                    val startTimeDiffer = TimeUtils.string2Millis(it.startTime) - nowTime
                    if (startTimeDiffer > 0) {
                        toast("促销活动暂未开始")
                    } else {
                        OrderSubmitActivity.buyNow(this, it.id, goodsNum, shopId)
                    }
                } else {
                    OrderSubmitActivity.buyNow(this, it.id, goodsNum, shopId)
                }
            }
        }, { specId, goodsNum -> // 加入购物车回调
            if (AccountManager.getToken().isEmpty()) { // 未登录，跳转登录
                LoginActivity.jump2Login(this@ProductDetailActivity2)
                return@ProductSpecPopupWindow
            }
            val map = hashMapOf("goods_id" to productId.toString(), "goods_num" to goodsNum.toString(), "shop_id" to shopId.toString())
            viewModel.addCart(map)
        }).apply {
            viewModel.productLiveData2.value?.response?.data?.let {
                initData(it)
            }
        }
    }

    var productId = 0//商品id
    var shopId = 0//门店id
    var activeType: Int = 0//活动类型

    override val layoutResId: Int = R.layout.activity_product_detail_2
    override fun setViewModel(): ProductViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleProduct


    private val recommendAdapter = ProductRecommendAdapter()

    override fun initUI() {
        with(tabProduct) {
            layoutManager = LinearLayoutManager(this@ProductDetailActivity2, LinearLayoutManager.HORIZONTAL, false)
            adapter = tabAdapter
        }


        with(rvProductRecommend) {
            layoutManager = GridLayoutManager(this@ProductDetailActivity2, 3, GridLayoutManager.VERTICAL, false)
            addItemDecoration(
                GridItemDecoration(
                    ScreenUtil.dip(this@ProductDetailActivity2, 8),
                    ScreenUtil.dip(this@ProductDetailActivity2, 8)
                )
            )
            adapter = recommendAdapter
        }
        recommendAdapter.setOnItemClickListener { adapter, view, position ->
            normalProduct(this, recommendAdapter.data[position].id, false, shopId = CustomApplication.getShopId())
        }
        recommendAdapter.addChildClickViewIds(R.id.tvProductAdd)
        recommendAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.tvProductAdd) {
                val map = hashMapOf("goods_id" to recommendAdapter.data[position].id.toString(), "goods_num" to "1", "shop_id" to shopId.toString())
                viewModel.addCart(map)
            }
        }

        // 设置页面的滚动监听
        scrollProduct.setOnScrollChangeListener(object : NestedScrollView.OnScrollChangeListener {
            private val maxChangeHeight =
                ScreenUtil.getScreenWidth(this@ProductDetailActivity2) * 2 / 3
            private val canBackTopHeight = ScreenUtil.getScreenHeight(this@ProductDetailActivity2) * 1.5

            override fun onScrollChange(
                v: NestedScrollView?,
                scrollX: Int,
                scrollY: Int,
                oldScrollX: Int,
                oldScrollY: Int
            ) {
                if (scrollY <= 10) tabProduct.visibility = View.INVISIBLE
                else tabProduct.visibility = View.VISIBLE
                // 判断顶部透明度
                if (scrollY <= maxChangeHeight) {
                    val alpha = scrollY.toFloat() / maxChangeHeight * 255
                    titleProduct.setLeftIcon(R.drawable.ic_back)
                        .setBackgroundColor(Color.argb(alpha.toInt(), 255, 255, 255))
                } else {
                    titleProduct.setLeftIcon(R.drawable.ic_arrow_left_black)
                        .setBackgroundColor(Color.WHITE)
                }
                // 判断tab的位置
//                when {
//                    scrollY < recommendView.top - titleProduct.height -> tabAdapter.selectedPosition = 0
//                    scrollY < detailView.top - titleProduct.height -> tabAdapter.selectedPosition = 1
//                    else -> tabAdapter.selectedPosition = 2
//                }
                // 判断回到顶部的按钮是否显示
                ivProductTop.visibility = if (scrollY < canBackTopHeight) View.GONE else View.VISIBLE
            }
        })
        // 设置Banner
        with(bannerProduct) {
            adapter = bannerAdapter
            getChildAt(0)?.overScrollMode = View.OVER_SCROLL_NEVER
            registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    // 判断是否滑动到特定页面
                    if (position == bannerAdapter.data.lastIndex &&
                        bannerAdapter.data.last().type == BannerUIEntity.PULL
                    ) {
                        // 滚动到商品详情
                        val detailTop = detailView.top
                        val scrollY = detailTop - titleProduct.height
                        scrollProduct.scrollTo(0, scrollY)
                        // 回滚到倒数第二个item
                        bannerProduct.postDelayed(300L) {
                            currentItem = bannerAdapter.data.lastIndex - 1
                        }
                    }
                    if (bannerAdapter.data[0].type == BannerUIEntity.VIDEO && position == 0) {
                        if (!bannerAdapter.data[0].userStop) GSYVideoManager.onResume()
                    } else if (bannerAdapter.data[0].type == BannerUIEntity.VIDEO && position > 0) {
                        if (GSYVideoManager.instance().isPlaying) {
                            bannerAdapter.data[0].userStop = false
                            GSYVideoManager.onPause()
                        }
                    }
                }
            })
        }

        // 回到顶部
        ivProductTop.setOnClickListener {
            scrollProduct.smoothScrollTo(0, 0)
        }
        // 收藏点击
        ivProductCollection.setOnClickListener {

            if (AccountManager.getToken().isEmpty()) {
                LoginActivity.jump2Login(this@ProductDetailActivity2)
                return@setOnClickListener
            }
            viewModel.productLiveData2.value?.response?.data?.let {
                viewModel.collectGoods(AccountManager.getToken(), shopId.toLong(), productId.toLong(), "0")
            }
        }
        //规格点击
        frame_group_spec.setOnClickListener {
            showSelectSpecDialog(isBuy = false, type = activeType)
        }
        // 客服点击
        tvProductService.setOnClickListener {
            val rxPermission = RxPermissions(this)
            rxPermission.request(Manifest.permission.CALL_PHONE)
                .subscribe {
                    if (it) {
                        val mobile = if (CustomApplication.getShopMobile().isEmpty())
                            ConfigManager.getCustomerMobile() else CustomApplication.getShopMobile()
                        if (mobile.isEmpty()) {
                            toast("暂无联系电话")
                            return@subscribe
                        }
                        val builder = AlertDialog.Builder(this)
                            .setTitle("联系客服")
                            .setMessage(mobile)
                            .setPositiveButton("确定") { dialog, which ->
                                dialog.cancel()
                                val intent = Intent(Intent.ACTION_CALL);
                                val data = Uri.parse("tel:${mobile}");
                                intent.data = data
                                startActivity(intent)
                            }
                            .setNegativeButton("取消") { dialog, which ->
                                dialog.cancel()
                            }
                        builder.show()
                    } else {
                        toast("请到设置中开启权限")
                    }
                }
        }
        // 加入购物车点击
        tvProductAddToCart.setOnClickListener {
            val map = hashMapOf("goods_id" to productId.toString(), "goods_num" to "1", "shop_id" to shopId.toString())
            viewModel.addCart(map)
        }
        // 立即购买点击
        tvProductBuyNow.setOnClickListener {
            showSelectSpecDialog(isBuy = true, type = activeType)
        }
        // 立即购买点击
        tvProductBuyNowActive.setOnClickListener {
            showSelectSpecDialog(isBuy = true, type = activeType)
        }
    }

    override fun initData() {
        productId = intent.getIntExtra(PRODUCT_ID, -1)
        shopId = intent.getIntExtra(SHOP_ID, -1)
        viewModel.getProduct2(productId, shopId)
    }

    override fun initViewModel() {
        // 商品数据观察者
        viewModel.productLiveData2.observe(this, Observer { it ->
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS)
                it.response?.let {
                    fillData(it)
                }
        })
        // 商品收藏观察者
        viewModel.collectProductLiveData.observe(this, Observer { it ->
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) {
                it.response?.let {
                    val msg = it.msg ?: return@let
                    val isCollect = !msg.contains("取消")
                    val drawable =
                        getDrawable(if (isCollect) R.drawable.ic_product_collection_selected else R.drawable.ic_product_collection)?.apply {
                            setBounds(0, 0, intrinsicWidth, intrinsicHeight)
                        }
                    ivProductCollection.setCompoundDrawables(null, drawable, null, null)
                    ivProductCollection.text =
                        getString(if (isCollect) R.string.collection_success else R.string.collection_product)
                    toast(msg)
                }
            }
        })
        // 商品加入购物车观察者
        viewModel.addCartLiveData.observe(this, Observer {
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS)
                toast(getString(R.string.add_cart_success))
        })
    }

    fun fillData(resp: ProductResponse2) {
        this.activeType = resp.data.activeType
        with(resp.data) {
            if (activeType == 0) {
                tvProductPrice.text = SpanUtil.setMoneySymbol(price, false)
                textBarPrice.text = SpanUtil.setMoneySymbol(price, true)
                tvProductEarn.visibility = View.GONE
                if (plusPrice.isNullOrEmpty()) {
                    llProductPush.visibility = View.GONE
                } else {
                    llProductPush.visibility = View.VISIBLE
                    tvProductPushPrice.text = SpanUtil.setMoneySymbol(plusPrice, false)
                }
            } else {
                tvProductPrice.text = SpanUtil.setMoneySymbol(activePrice, true)
                textBarPrice.text = SpanUtil.setMoneySymbol(activePrice, true)
                tvProductEarn.text = SpanUtil.setMoneySymbol(price, false)
                tvProductEarn.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
            }
            textBarPriceEarn.text = SpanUtil.setMoneySymbol(price, false)
            textBarPriceEarn.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG
            tvProductName.text = goodsName
            tvProductSale.text = "销量:${salesSum}"
            // 判断热卖新品是否可见
            tvProductSellTag.visibility =
                if (TextUtils.equals(isHot, "1")) View.VISIBLE else View.GONE
            tvProductNewTag.visibility =
                if (TextUtils.equals(isNew, "1")) View.VISIBLE else View.GONE
            //  判断品牌是否可见
            brand?.let {
//                viewBrand.visibility = View.VISIBLE
//                tvProductBrandName.text = it.name
//                ImageUtils.loadCircleImage(this@ProductDetailActivity2, ivProductBrand, it.image ?: "")
            }

            if (activeType == 0) {
                tvProductAddToCart.visibility = View.VISIBLE
                tvProductBuyNow.visibility = View.VISIBLE
                frame_group_bar.visibility = View.GONE
                tvProductBuyNowActive.visibility = View.GONE
            } else {
                tvProductAddToCart.visibility = View.GONE
                tvProductBuyNow.visibility = View.GONE
                frame_group_bar.visibility = View.VISIBLE
                tvProductBuyNowActive.visibility = View.VISIBLE
                tvProductName.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
            }
            // 构造顶部Banner数据
            val list = mutableListOf<BannerUIEntity>()
            if (video.isNotEmpty()) list.add(BannerUIEntity(BannerUIEntity.VIDEO, video, image))
            images.forEach { list.add(BannerUIEntity(BannerUIEntity.IMAGE, null, it)) }
            if (list.isNotEmpty()) {
                list.add(BannerUIEntity(BannerUIEntity.PULL, null, null))
                bannerProduct.offscreenPageLimit = list.size
            }
            bannerAdapter.setNewData(list)

            // 判断是否已收藏
            val drawable =
                getDrawable(if (isCollect) R.drawable.ic_product_collection_selected else R.drawable.ic_product_collection)?.apply {
                    setBounds(0, 0, intrinsicWidth, intrinsicHeight)
                }
            ivProductCollection.setCompoundDrawables(null, drawable, null, null)
            ivProductCollection.text =
                getString(if (isCollect) R.string.collection_success else R.string.collection_product)

            if (group.size == 0) {
                recommendView.visibility = View.GONE
            } else {
                recommendView.visibility = View.VISIBLE
                recommendAdapter.setNewData(group)
            }

            //倒计时时间设置
            val nowTime = TimeUtils.getNowMills()
            when (activeType) {
                1 -> {
                    frame_price.visibility = View.GONE
                    // 限时促销
                    val startTimeDiffer = TimeUtils.string2Millis(startTime) - nowTime
                    val endTimeDiffer = TimeUtils.string2Millis(endTime) - nowTime
                    //初始化倒计时时间
                    when {
                        startTimeDiffer > 0 -> {
                            initTime(startTimeDiffer) // 距离开始促销
                            textTimeTitle.text = "距开始促销还剩"
                        }
                        endTimeDiffer > 0 -> {
                            initTime(endTimeDiffer) // 距离结束促销
                            textTimeTitle.text = "距结束促销还剩"
                        }
                        else -> null
                    }
                }
                2 -> {
                    frame_price.visibility = View.GONE
                    // 预售
                    val endTimeDiffer = TimeUtils.string2Millis(endTime) - nowTime
                    initTime(endTimeDiffer)
                    textTimeTitle.text = "距预售时间还剩"
                }
                else -> {
                    frame_price.visibility = View.VISIBLE
                }
            }

        }
    }

    private fun showSelectSpecDialog(isBuy: Boolean, type: Int = 0) {
        productSpecPopupWindow.setMode(isBuy, type)
        productSpecPopupWindow.showPopupWindow()
    }


    private var timeDay: Long = 0//天
    private var timeHour: Long = 0//时
    private var timeMin: Long = 0//分
    private var timeSec: Long = 0//秒

    private fun initTime(differ: Long) {
        timeDay = differ / (1000 * 60 * 60 * 24) //以天数为单位取整
        timeHour = differ / (60 * 60 * 1000) - timeDay * 24 //以小时为单位取整
        timeMin = differ / (60 * 1000) - timeDay * 24 * 60 - timeHour * 60 //以分钟为单位取整
        timeSec = differ / 1000 - timeDay * 24 * 60 * 60 - timeHour * 60 * 60 - timeMin * 60 //秒
        val timer = Timer()
        val task: TimerTask = object : TimerTask() {
            override fun run() {
                runOnUiThread {
                    if (timeDay.toInt() == 0 && timeHour.toInt() == 0
                        && timeMin.toInt() == 0 && timeSec.toInt() == 0
                    ) {
                        timer.cancel()
                        initData()
                    } else {
                        computeTime()
                        textDay.text = if (timeDay >= 10) timeDay.toString() else "0${timeDay}"
                        textHour.text = if (timeHour >= 10) timeHour.toString() else "0${timeHour}"
                        textMinute.text = if (timeMin >= 10) timeMin.toString() else "0${timeMin}"
                        textSecond.text = if (timeSec >= 10) timeSec.toString() else "0${timeSec}"
                    }
                }
            }
        }
        timer.schedule(task, 0, 1000)
    }

    private fun computeTime() {
        timeSec--
        if (timeSec < 0) {
            timeMin--
            timeSec = 59
            if (timeMin < 0) {
                timeMin = 59
                timeHour--
                if (timeHour < 0) {
                    // 倒计时结束
                    timeHour = 23
                    timeDay--
                }
            }
        }
    }
}